<template>
	<div class="app">
		<div id="aiEditor" ref="divRef" style="padding: 0;margin: 0">
			<div class="aie-container" style="background-color: #f3f4f6">
				<div class="aie-header-panel">
					<div class="aie-container-header" style="background: #fff;"></div>
				</div>
				<div class="aie-main">
					<!---左侧面板--->
					<div class="aie-menu-button" v-if="!showDirectory" style="opacity: 1; left: 0px;" @click="openDirectory">目录大纲</div>
					<div class="aie-menu-content" :class="{hidden: !showDirectory}">
						<div class="aie-directory">
							<div class="directory-header">
								<h5>文档目录</h5>
								<div class="btn" @click="closeDirectory" title="关闭">
									<svg t="1749694501167" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="12794" width="12" height="12"><path d="M963.995371 856.080569c-1.092891 27.205619-11.259438 54.104245-32.019251 74.872245-20.766976 20.759813-47.666626 30.92636-74.865081 32.019251-30.267351 1.242294-60.827367-8.916067-83.930551-32.019251L515.75758 673.522744 258.334673 930.952814c-23.103184 23.103184-53.6632 33.262568-83.930551 32.019251-27.198455-1.092891-54.097082-11.259438-74.865081-32.019251-20.759813-20.766976-30.92636-47.666626-32.019251-74.872245-1.242294-30.267351 8.916067-60.820204 32.019251-83.930551l257.422907-257.414721-257.422907-257.422907c-23.103184-23.110347-33.262568-53.6632-32.019251-83.930551 1.092891-27.205619 11.259438-54.105269 32.019251-74.872245 20.767999-20.75265 47.666626-30.919197 74.865081-32.012088 30.267351-1.25048 60.827367 8.908904 83.930551 32.012088l257.422907 257.43007L773.180488 98.508571c23.103184-23.103184 53.6632-33.262568 83.930551-32.012088 27.198455 1.092891 54.097082 11.259438 74.865081 32.012088 20.759813 20.767999 30.92636 47.666626 32.019251 74.872245 1.242294 30.267351-8.916067 60.820204-32.019251 83.930551l-257.422907 257.422907 257.422907 257.414721C955.079304 795.260365 965.238688 825.812195 963.995371 856.080569z" p-id="12795" fill="#81868F"></path></svg>
								</div>
							</div>
							<div id="outline"></div>
						</div>
					</div>
					<!---编辑区域--->
					<div class="aie-container-panel">
						<div class="aie-container-panel-box">
							<div class="aie-container-main"></div>
						</div>
					</div>

					<!---AI对话--->
					<div class="aie-ai-content" :class="{hidden: !showChatPanel}">
						<div class="aie-ai-chat">
							<div class="chat-tabar">
								<div :class="`tab ${tabType == 'chat' ? 'active' : ''}`" @click="ontab('chat')">
									<span class="icon-tab"></span>
									AI问答
								</div>
								<div class="tab-op" v-if="tabType === 'chat'">
									<div class="btn" @click="newChat" title="新建对话">
										<svg t="1749694261439" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9718" id="mx_n_1749694261440" width="12" height="12"><path d="M416 416V32h192v384H992v192H608V992h-192V608H32v-192h384z" p-id="9719" fill="#81868F"></path></svg>
									</div>
									<div class="btn" @click="clearHistory" title="清除历史">
										<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
											<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"
												fill="#81868F" />
										</svg>
									</div>
									<div class="btn" @click="closeChat" title="关闭">
										<svg t="1749694501167" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="12794" id="mx_n_1749694501168" width="12" height="12"><path d="M963.995371 856.080569c-1.092891 27.205619-11.259438 54.104245-32.019251 74.872245-20.766976 20.759813-47.666626 30.92636-74.865081 32.019251-30.267351 1.242294-60.827367-8.916067-83.930551-32.019251L515.75758 673.522744 258.334673 930.952814c-23.103184 23.103184-53.6632 33.262568-83.930551 32.019251-27.198455-1.092891-54.097082-11.259438-74.865081-32.019251-20.759813-20.766976-30.92636-47.666626-32.019251-74.872245-1.242294-30.267351 8.916067-60.820204 32.019251-83.930551l257.422907-257.414721-257.422907-257.422907c-23.103184-23.110347-33.262568-53.6632-32.019251-83.930551 1.092891-27.205619 11.259438-54.105269 32.019251-74.872245 20.767999-20.75265 47.666626-30.919197 74.865081-32.012088 30.267351-1.25048 60.827367 8.908904 83.930551 32.012088l257.422907 257.43007L773.180488 98.508571c23.103184-23.103184 53.6632-33.262568 83.930551-32.012088 27.198455 1.092891 54.097082 11.259438 74.865081 32.012088 20.759813 20.767999 30.92636 47.666626 32.019251 74.872245 1.242294 30.267351-8.916067 60.820204-32.019251 83.930551l-257.422907 257.422907 257.422907 257.414721C955.079304 795.260365 965.238688 825.812195 963.995371 856.080569z" p-id="12795" fill="#81868F"></path></svg>
									</div>
								</div>
								<!-- <div :class="`tab ${tabType == 'sum' ? 'active' : ''}` " @click="ontab('sum')">总结</div> -->
							</div>
							<div class="chat-main">
								<div class="panel" v-if="tabType === 'chat'">
									<div class="chat-content">
										<div v-for="(message, index) in messages" :key="index" :class="`message ${message.role}`">
											<div class="message-bubble">
												<div class="message-content" @click="sendMessage1(message)">
													<span v-html="message.content"></span>
												</div>
											</div>
											<div class="message-actions user" v-if="message.role === 'user'">
												<div class="action-btn" title="复制" @click="copyMessage(message.content)">
													<svg width="24" height="24" viewBox="0 0 24 24" fill="none"
														xmlns="http://www.w3.org/2000/svg">
														<path fill-rule="evenodd" clip-rule="evenodd"
															d="M9.917 6.375h7.291v9.792h1.042V6.333a1 1 0 0 0-1-1H7.417v1.042h2.5ZM6.375 17.21v-8.75h8.75v8.75h-8.75ZM5.333 8.25c0-.46.373-.833.834-.833h9.166c.46 0 .834.373.834.833v9.167c0 .46-.374.833-.834.833H6.167a.833.833 0 0 1-.834-.833V8.25Z"
															fill="#81868F"></path>
													</svg>
												</div>
												<div class="action-btn" title="重写指令" @click="rewriteInstruction(index)">
													<svg width="24" height="24" viewBox="0 0 24 24" fill="none"
														xmlns="http://www.w3.org/2000/svg">
														<path fill-rule="evenodd" clip-rule="evenodd"
															d="m15.588 5.456 2.956 2.956a.418.418 0 0 1 0 .59L9.587 17.96a.418.418 0 0 1-.228.117l-3.54.584a.418.418 0 0 1-.48-.48l.584-3.54a.418.418 0 0 1 .117-.228l8.957-8.957a.418.418 0 0 1 .591 0ZM13.355 8.57l-6.437 6.436-.41 2.484 2.484-.41 6.437-6.436-2.074-2.074Zm.736-.737 2.074 2.074 1.202-1.201-2.075-2.074-1.2 1.201Z"
															fill="#81868F"></path>
													</svg>
												</div>
											</div>
											<div class="message-actions assistant" v-if="message.role === 'assistant'">
												<div class="action-btn" title="应用" @click="applyMessage(message.content)">
													<svg t="1747798388245" viewBox="0 0 1024 1024" version="1.1"
														xmlns="http://www.w3.org/2000/svg" p-id="2044" width="18" height="18">
														<path
															d="M736.72 440a23.44 23.44 0 1 0 0-46.8H325.2l60.48-61.6a23.44 23.44 0 0 0 6.32-16.56 22.8 22.8 0 0 0-6.96-16.48 23.36 23.36 0 0 0-33.12 0L213.68 440zM219.84 617.12a23.44 23.44 0 0 0 23.44 23.44h414.56l-61.44 61.44a23.36 23.36 0 0 0 0 33.12 23.36 23.36 0 0 0 33.12 0l141.44-141.36h-528a23.44 23.44 0 0 0-23.12 23.36z"
															p-id="2045" fill="#81868F"></path>
														<path
															d="M512 72a440 440 0 1 0 440 440A440.48 440.48 0 0 0 512 72z m0 59.92A380.08 380.08 0 1 1 131.92 512 380.48 380.48 0 0 1 512 131.92z"
															p-id="2046" fill="#81868F"></path>
													</svg>
												</div>
												<div class="action-btn" title="追加" @click="insertMessage(message.content)">
													<svg t="1747797882478" viewBox="0 0 1024 1024" version="1.1"
														xmlns="http://www.w3.org/2000/svg" p-id="4623" width="17" height="17">
														<path
															d="M928.88 789.87V548.29a35.35 35.35 0 0 0-70.66 0V790.7a69.13 69.13 0 0 1-69.17 69.07H235.48a69.13 69.13 0 0 1-69.17-69.07V237.4a69.12 69.12 0 0 1 69.17-69.06h242.6a35.16 35.16 0 1 0 0-70.31H237.21c-76.4 0-138.33 61.84-138.33 138.13v553.71c0 76.29 61.93 138.13 138.33 138.13h553.33c76.4 0 138.34-61.84 138.34-138.13z m-242-451.57v140.55a34.45 34.45 0 0 0 68.89 0V338.3h139.32a33.74 33.74 0 1 0 0-67.47H755.82V132.42a34.45 34.45 0 0 0-68.89-0.06v138.47H546.49a33.74 33.74 0 1 0 0 67.47z"
															p-id="4624" fill="#81868F"></path>
													</svg>
												</div>
												<div class="action-btn" title="复制" @click="copyMessage(message.content)">
													<svg width="24" height="24" viewBox="0 0 24 24" fill="none"
														xmlns="http://www.w3.org/2000/svg">
														<path fill-rule="evenodd" clip-rule="evenodd"
															d="M9.917 6.375h7.291v9.792h1.042V6.333a1 1 0 0 0-1-1H7.417v1.042h2.5ZM6.375 17.21v-8.75h8.75v8.75h-8.75ZM5.333 8.25c0-.46.373-.833.834-.833h9.166c.46 0 .834.373.834.833v9.167c0 .46-.374.833-.834.833H6.167a.833.833 0 0 1-.834-.833V8.25Z"
															fill="#81868F"></path>
													</svg>
												</div>
												<div class="action-btn" title="重新生成" @click="regenerateMessage(index)">
													<svg width="21" height="20" viewBox="0 0 21 20" fill="none"
														xmlns="http://www.w3.org/2000/svg">
														<path fill-rule="evenodd" clip-rule="evenodd"
															d="M14.47 6.992a5.313 5.313 0 1 0-.226 6.363h1.272a6.354 6.354 0 1 1-.142-6.885l1.405-.811v4.636l-4.015-2.318 1.706-.985Z"
															fill="#81868F"></path>
													</svg>
												</div>
											</div>
										</div>

										<!-- 添加loading效果 -->
										<div v-if="isLoading" class="message assistant">
											<div class="message-bubble">
												<div class="message-content">
													<div class="loading-dots">
														<div class="dot"></div>
														<div class="dot"></div>
														<div class="dot"></div>
													</div>
												</div>
											</div>
										</div>
									</div>
									<div class="chat-input">
										<textarea class="input-text" ref="textareaRef" placeholder="请输入您的需求..."
											:style="{ height: textareaHeight }" @input="adjustTextareaHeight"
											@keydown.enter.prevent="handleEnterKey"></textarea>
									</div>
									<div class="btn-box">
										<div class="btn-group left">
											<div class="optimize-btn" @click="optimizePrompt">优化提示词</div>
											<div class="clear-btn" @click="clearInput">清除</div>
										</div>
										<div class="btn-group right">
											<button class="btn stop-btn" v-if="isLoading" @click="stopGeneration">停止</button>
											<div class="send-btn" v-else @click="sendMessage"></div>
										</div>
									</div>
								</div>

								<div class="panel" v-if="tabType === 'sum'">
									这里是总结的内容
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="aie-container-footer"></div>
			</div>
		</div>

		<!--消息提示-->
		<div class="toast-container" v-if="showToast">
			<div class="toast-message" :class="toastType">
				<span class="toast-icon">
					<svg v-if="toastType === 'success'" t="1749695190792" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="14675" width="16" height="16"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 0 1-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z" p-id="14676" fill="#fff"></path></svg>
					<svg v-else-if="toastType === 'error'" t="1749695190792" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="14675" width="16" height="16"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-0.3L512 563.4l-99.3 118.4-66.1.3c-4.4 0-8-3.5-8-8 0-1.9.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 0 1-1.9-5.2c0-4.4 3.6-8 8-8l66.1.3L512 464.6l99.3-118.4 66-.3c4.4 0 8 3.5 8 8 0 1.9-.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z" p-id="14676" fill="#fff"></path></svg>
					<svg v-else t="1749695190792" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="14675" width="16" height="16"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm-32 232c0-4.4 3.6-8 8-8h48c4.4 0 8 3.6 8 8v272c0 4.4-3.6 8-8 8h-48c-4.4 0-8-3.6-8-8V296zm32 440a48.01 48.01 0 0 1 0-96 48.01 48.01 0 0 1 0 96z" p-id="14676" fill="#fff"></path></svg>
				</span>
				<span>{{ toastMessage }}</span>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { AiEditor } from "aieditor";
import "aieditor/dist/style.css"
import { onMounted, onUnmounted, ref } from "vue";
import { marked } from 'marked';
import { parseHtml } from '@/utils/parseHtml';

const emit = defineEmits();

const {
	llm_url,
	llm_key,
	llm_model,
	export_api,
	import_api,
	showTools,
} = defineProps({
	llm_url: { required: true, type: String,default: () => ''},
	llm_key: {required: true,type: String,default: () => ''},
	llm_model: {required: true,type: String,default: () => ''},
	export_api: {required: true,type: String,default: () => ''},
	import_api: {required: true,type: String,default: () => ''},
	showTools: {required: false,type: Boolean,default: () => true}
})

/** 变量区域 */

const divRef = ref();
const textareaRef = ref();
let aiEditor: AiEditor | null = null;
const tabType = ref('chat');
const textareaHeight = ref('auto');
const messages = ref([] as Array<{ role: string, content: any }>);

/** 消息提示变量 */
const showToast = ref(false);
const toastTimeout = ref<number | null>(null);
const toastMessage = ref('');
const toastType = ref<'success' | 'error' | 'warning'>('success'); 

// 封装Toast提示方法
const showToastMessage = (message: string, type: 'success' | 'error' | 'warning' = 'success', duration: number = 2000) => {
    showToast.value = true;
    toastMessage.value = message;
    toastType.value = type;
    if (toastTimeout.value) {
        clearTimeout(toastTimeout.value);
    }
	// @ts-ignore
    toastTimeout.value = setTimeout(() => {
        showToast.value = false;
    }, duration);
}

/** loading 数据加载变量 */
const isLoading = ref(false);

const abortController = ref<AbortController | null>(null);

onMounted(() => {
	aiEditor = new AiEditor({
		element: divRef.value as Element,
		placeholder: "点击输入内容...",
		content: '',
		draggable: false,
		contentRetention: false,
		ai: {
			models: {
				custom: {
					url: llm_url + '/stream',
					headers: () => {
						return {
							"Content-Type": "application/json",
							"Authorization": `Bearer ${llm_key}`
						}
					},
					wrapPayload: (message: string) => {
						const prompt = {
							"model": llm_model,
							"messages": [
								{
									"content": message,
									"role": "user"
								}
							],
							"stream": true
						}
						return JSON.stringify(prompt)
					},
					parseMessage: (message: string) => {
						console.log(message)
						if (message === "[DONE]") return { role: "assistant", content: "" };

						try {
							const data = JSON.parse(message);
							// const content = data.choices?.[0]?.delta?.content || '';
							const content = data.result.output.text || ""
							return { role: "assistant", content };
						} catch {
							return { role: "assistant", content: "模型返回错误" };
						}
					},
					//protocol: "sse"
				},
			},
			commands: [],
			bubblePanelMenus:[
				{
					prompt: `<content>{content}</content>\n请帮我优化一下这段内容，并直接返回优化后的结果。\n注意：你应该先判断一下这句话是中文还是英文，如果是中文，请给我返回中文的内容，如果是英文，请给我返回英文内容，只需要返回内容即可，不需要告知我是中文还是英文。`,
					icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M15.1986 9.94447C14.7649 9.5337 14.4859 8.98613 14.4085 8.39384L14.0056 5.31138L11.275 6.79724C10.7503 7.08274 10.1433 7.17888 9.55608 7.06948L6.49998 6.50015L7.06931 9.55625C7.17871 10.1435 7.08257 10.7505 6.79707 11.2751L5.31121 14.0057L8.39367 14.4086C8.98596 14.4861 9.53353 14.7651 9.94431 15.1987L12.0821 17.4557L13.4178 14.6486C13.6745 14.1092 14.109 13.6747 14.6484 13.418L17.4555 12.0823L15.1986 9.94447ZM15.2238 15.5079L13.0111 20.1581C12.8687 20.4573 12.5107 20.5844 12.2115 20.442C12.1448 20.4103 12.0845 20.3665 12.0337 20.3129L8.49229 16.5741C8.39749 16.474 8.27113 16.4096 8.13445 16.3918L3.02816 15.7243C2.69958 15.6814 2.46804 15.3802 2.51099 15.0516C2.52056 14.9784 2.54359 14.9075 2.5789 14.8426L5.04031 10.3192C5.1062 10.1981 5.12839 10.058 5.10314 9.92253L4.16 4.85991C4.09931 4.53414 4.3142 4.22086 4.63997 4.16017C4.7126 4.14664 4.78711 4.14664 4.85974 4.16017L9.92237 5.10331C10.0579 5.12855 10.198 5.10637 10.319 5.04048L14.8424 2.57907C15.1335 2.42068 15.4979 2.52825 15.6562 2.81931C15.6916 2.88421 15.7146 2.95507 15.7241 3.02833L16.3916 8.13462C16.4095 8.2713 16.4739 8.39766 16.5739 8.49245L20.3127 12.0338C20.5533 12.2617 20.5636 12.6415 20.3357 12.8821C20.2849 12.9357 20.2246 12.9795 20.1579 13.0112L15.5078 15.224C15.3833 15.2832 15.283 15.3835 15.2238 15.5079ZM16.0206 17.435L17.4348 16.0208L21.6775 20.2634L20.2633 21.6776L16.0206 17.435Z"></path></svg>`,
					title: 'improve-writing',
				},
				// {
				// 	prompt: `<content>{content}</content>\n请帮我检查一下这段内容，是否有拼写错误或者语法上的错误。\n注意：你应该先判断一下这句话是中文还是英文，如果是中文，请给我返回中文的内容，如果是英文，请给我返回英文内容，只需要返回内容即可，不需要告知我是中文还是英文。`,
				// 	icon: ` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 19C12.8284 19 13.5 19.6716 13.5 20.5C13.5 21.3284 12.8284 22 12 22C11.1716 22 10.5 21.3284 10.5 20.5C10.5 19.6716 11.1716 19 12 19ZM6.5 19C7.32843 19 8 19.6716 8 20.5C8 21.3284 7.32843 22 6.5 22C5.67157 22 5 21.3284 5 20.5C5 19.6716 5.67157 19 6.5 19ZM17.5 19C18.3284 19 19 19.6716 19 20.5C19 21.3284 18.3284 22 17.5 22C16.6716 22 16 21.3284 16 20.5C16 19.6716 16.6716 19 17.5 19ZM13 2V4H19V6L17.0322 6.0006C16.2423 8.3666 14.9984 10.5065 13.4107 12.302C14.9544 13.6737 16.7616 14.7204 18.7379 15.3443L18.2017 17.2736C15.8917 16.5557 13.787 15.3326 12.0005 13.7257C10.214 15.332 8.10914 16.5553 5.79891 17.2734L5.26257 15.3442C7.2385 14.7203 9.04543 13.6737 10.5904 12.3021C9.46307 11.0285 8.50916 9.58052 7.76789 8.00128L10.0074 8.00137C10.5706 9.03952 11.2401 10.0037 11.9998 10.8772C13.2283 9.46508 14.2205 7.81616 14.9095 6.00101L5 6V4H11V2H13Z"></path></svg>`,
				// 	title: 'check-spelling-and-grammar',
				// },
				{
					prompt: `<content>{content}</content>\n这句话的内容较长，帮我简化一下这个内容，并直接返回简化后的内容结果。\n注意：你应该先判断一下这句话是中文还是英文，如果是中文，请给我返回中文的内容，如果是英文，请给我返回英文内容，只需要返回内容即可，不需要告知我是中文还是英文。`,
					icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M21 6.75736L19 8.75736V4H10V9H5V20H19V17.2426L21 15.2426V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V6.75736ZM21.7782 8.80761L23.1924 10.2218L15.4142 18L13.9979 17.9979L14 16.5858L21.7782 8.80761Z"></path></svg>`,
					title: 'make-shorter',
				},
				{
					prompt: `<content>{content}</content>\n这句话的内容较简短，帮我简单的优化和丰富一下内容，并直接返回优化后的结果。注意：优化的内容不能超过原来内容的 2 倍。\n注意：你应该先判断一下这句话是中文还是英文，如果是中文，请给我返回中文的内容，如果是英文，请给我返回英文内容，只需要返回内容即可，不需要告知我是中文还是英文。`,
					icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2C20.5523 2 21 2.44772 21 3V6.757L19 8.757V4H5V20H19V17.242L21 15.242V21C21 21.5523 20.5523 22 20 22H4C3.44772 22 3 21.5523 3 21V3C3 2.44772 3.44772 2 4 2H20ZM21.7782 8.80761L23.1924 10.2218L15.4142 18L13.9979 17.9979L14 16.5858L21.7782 8.80761ZM13 12V14H8V12H13ZM16 8V10H8V8H16Z"></path></svg>`,
					title: 'make-longer',
				},
			],
			// menus: [
			// 	{
			// 		icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"></path><path d="M4 18.9997H20V13.9997H22V19.9997C22 20.552 21.5523 20.9997 21 20.9997H3C2.44772 20.9997 2 20.552 2 19.9997V13.9997H4V18.9997ZM16.1716 6.9997L12.2218 3.04996L13.636 1.63574L20 7.9997L13.636 14.3637L12.2218 12.9495L16.1716 8.9997H5V6.9997H16.1716Z"></path></svg>`,
			// 		name: `AI 续写`,
			// 		prompt: "{content}\n\n请帮我继续扩展以上这段文字的内容。\n注意：你应该先判断一下这句话是中文还是英文，如果是中文，请给我返回中文的内容，如果是英文，请给我返回英文内容，只需要返回内容即可，不需要告知我是中文还是英文。",
			// 		text: "selected",
			// 		model: "auto",
			// 	},
			// 	{
			// 		icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0z"></path><path d="M15 5.25C16.7949 5.25 18.25 3.79493 18.25 2H19.75C19.75 3.79493 21.2051 5.25 23 5.25V6.75C21.2051 6.75 19.75 8.20507 19.75 10H18.25C18.25 8.20507 16.7949 6.75 15 6.75V5.25ZM4 7C4 5.89543 4.89543 5 6 5H13V3H6C3.79086 3 2 4.79086 2 7V17C2 19.2091 3.79086 21 6 21H18C20.2091 21 22 19.2091 22 17V12H20V17C20 18.1046 19.1046 19 18 19H6C4.89543 19 4 18.1046 4 17V7Z"></path></svg>`,
			// 		name: `AI 优化`,
			// 		prompt: "{content}\n\n请帮我优化以上这段文字的内容，并返回结果\n注意：你应该先判断一下这句话是中文还是英文，如果是中文，请给我返回中文的内容，如果是英文，请给我返回英文内容，只需要返回内容即可，不需要告知我是中文还是英文。",
			// 		text: "selected",
			// 		model: "auto",
			// 	},
			// ]
		},
		toolbarKeys: showTools ? [
			"undo", "redo", "brush", "eraser",
			"|", "heading", "font-family", "font-size",
			"|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript", "hr", "todo", "emoji",
			"|", "highlight", "font-color",
			"|", "align", "line-height",
			"|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
			"|", "image", "video", "attachment", "quote", "code-block", "table",
			"|", "printer", "fullscreen", "source-code",
			"|", {
				icon: '<svg t="1749699643593" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="19289" width="256" height="256"><path d="M915.2 224c0-19.2-12.8-38.4-38.4-32H582.4V115.2h-51.2L108.8 192v640c140.8 25.6 281.6 44.8 422.4 70.4h57.6V832h275.2c12.8 0 32 0 44.8-6.4 12.8-19.2 6.4-38.4 6.4-57.6V224zM416 633.6c-12.8 6.4-38.4 0-57.6 0-12.8-57.6-25.6-115.2-38.4-179.2-12.8 57.6-25.6 121.6-38.4 179.2-19.2 0-38.4 0-51.2-6.4-12.8-76.8-32-160-44.8-243.2h44.8c6.4 57.6 19.2 115.2 25.6 179.2 12.8-57.6 25.6-121.6 38.4-179.2h51.2c12.8 64 25.6 121.6 38.4 185.6 12.8-64 19.2-128 32-192h57.6c-19.2 83.2-38.4 172.8-57.6 256z m473.6 172.8H582.4v-70.4h236.8v-38.4H582.4v-44.8h236.8v-38.4H582.4v-44.8h236.8v-38.4H582.4v-44.8h236.8V448H582.4v-44.8h236.8v-38.4H582.4V320h236.8v-38.4H582.4v-64h300.8v588.8z m0 0" p-id="19290"></path></svg>',
				onClick: () => {
					importDocument();
				},
				tip: "导入Word"
			},
			{
				icon: '<svg t="1748915744021" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8398" width="256" height="256"><path d="M517.333333 280.8h-6.506666v45.92H517.333333a27.146667 27.146667 0 0 0 11.573334-1.813333 12.266667 12.266667 0 0 0 5.333333-6.293334 40.48 40.48 0 0 0 1.92-14.613333 28.586667 28.586667 0 0 0-4.32-18.293333 18.613333 18.613333 0 0 0-14.506667-4.906667zM431.04 278.72h-6.08a5.333333 5.333333 0 0 0-5.333333 5.333333v6.453334a5.333333 5.333333 0 0 0 5.333333 5.333333h5.653333a42.666667 42.666667 0 0 0 6.72-1.173333 6.986667 6.986667 0 0 0 4.213334-2.613334 7.946667 7.946667 0 0 0 1.6-4.906666 7.733333 7.733333 0 0 0-2.56-6.24 15.68 15.68 0 0 0-9.546667-2.186667z" p-id="8399"></path><path d="M625.226667 386.88V220.64a5.333333 5.333333 0 0 0-5.333334-5.333333h-506.133333a5.333333 5.333333 0 0 0-5.333333 5.333333v166.24a5.333333 5.333333 0 0 0 5.333333 5.333333h506.133333a5.333333 5.333333 0 0 0 5.333334-5.333333zM287.626667 268.266667l-16 73.333333a5.333333 5.333333 0 0 1-5.333334 4.16h-17.173333a5.333333 5.333333 0 0 1-5.333333-3.893333l-12.16-43.52a1.6 1.6 0 0 0-3.04 0l-11.84 43.52a5.333333 5.333333 0 0 1-5.333334 3.893333h-16.906666a5.333333 5.333333 0 0 1-5.333334-4.16L172.96 268.266667a5.333333 5.333333 0 0 1 5.333333-6.506667H192a5.333333 5.333333 0 0 1 5.333333 4.373333l6.773334 36a1.6 1.6 0 0 0 3.093333 0l10.08-36.533333a5.333333 5.333333 0 0 1 5.333333-3.946667h16.48a5.333333 5.333333 0 0 1 5.333334 3.946667l10.133333 36.48a1.6 1.6 0 0 0 3.093333 0l6.773334-35.946667a5.333333 5.333333 0 0 1 5.333333-4.373333H282.666667a5.333333 5.333333 0 0 1 4.96 6.506667z m86.666666 59.04a35.413333 35.413333 0 0 1-14.293333 14.666666 47.573333 47.573333 0 0 1-23.36 5.333334 53.333333 53.333333 0 0 1-23.52-4.533334 35.306667 35.306667 0 0 1-15.093333-14.293333A48 48 0 0 1 292.213333 304a45.706667 45.706667 0 0 1 75.733334-32 42.666667 42.666667 0 0 1 11.306666 31.52 51.733333 51.733333 0 0 1-4.96 23.786667z m93.173334 18.453333h-17.386667a5.333333 5.333333 0 0 1-4.693333-2.773333L433.013333 320a19.146667 19.146667 0 0 0-4.693333-6.453333 10.666667 10.666667 0 0 0-6.346667-1.973334h-2.293333v28.746667a5.333333 5.333333 0 0 1-5.333333 5.333333H398.933333a5.333333 5.333333 0 0 1-5.333333-5.333333V267.093333a5.333333 5.333333 0 0 1 5.333333-5.333333h37.92a62.613333 62.613333 0 0 1 18.4 2.08 19.786667 19.786667 0 0 1 10.24 7.68 22.88 22.88 0 0 1 3.84 13.6 23.626667 23.626667 0 0 1-2.986666 12.053333 22.88 22.88 0 0 1-8.213334 8.213334 30.346667 30.346667 0 0 1-9.066666 3.306666 27.84 27.84 0 0 1 6.72 3.093334 26.933333 26.933333 0 0 1 4.16 4.426666 30.4 30.4 0 0 1 3.626666 5.333334l8.586667 16.586666a5.333333 5.333333 0 0 1-4.693333 7.626667z m91.626666-21.333333a35.146667 35.146667 0 0 1-8.533333 12.426666A27.093333 27.093333 0 0 1 538.666667 343.466667a59.36 59.36 0 0 1-15.466667 2.293333h-33.013333a5.333333 5.333333 0 0 1-5.333334-5.333333V267.093333a5.333333 5.333333 0 0 1 5.333334-5.333333h33.226666a46.666667 46.666667 0 0 1 18.4 3.093333 30.186667 30.186667 0 0 1 11.626667 8.906667 36.053333 36.053333 0 0 1 6.56 13.44 62.08 62.08 0 0 1 2.08 16 56.96 56.96 0 0 1-2.986667 21.173333z" p-id="8400"></path><path d="M335.573333 280a16 16 0 0 0-12.64 5.333333 28.533333 28.533333 0 0 0-4.746666 18.666667 28.266667 28.266667 0 0 0 4.746666 18.293333 17.92 17.92 0 0 0 25.813334 0 31.146667 31.146667 0 0 0 4.586666-19.52 25.813333 25.813333 0 0 0-4.8-17.333333 16.266667 16.266667 0 0 0-12.96-5.44z" p-id="8401"></path><path d="M912 106.666667H201.173333a5.333333 5.333333 0 0 0-5.333333 5.333333v64a5.333333 5.333333 0 0 0 5.333333 5.333333H837.333333a5.333333 5.333333 0 0 1 5.333334 5.333334v510.666666a5.333333 5.333333 0 0 1-1.546667 3.733334l-88.213333 140.053333a5.333333 5.333333 0 0 1-3.733334 1.546667H275.84a5.333333 5.333333 0 0 1-5.333333-5.333334V434.08a5.333333 5.333333 0 0 0-5.333334-5.333333h-64a5.333333 5.333333 0 0 0-5.333333 5.333333V912a5.333333 5.333333 0 0 0 5.333333 5.333333h578.88a5.333333 5.333333 0 0 0 3.786667-1.546666l131.946667-183.786667a5.333333 5.333333 0 0 0 1.546666-3.786667V112a5.333333 5.333333 0 0 0-5.333333-5.333333z" p-id="8402"></path><path d="M575.52 512h-36.16a5.333333 5.333333 0 0 0-5.333333 3.946667c-16 64-43.413333 161.28-52.053334 202.986666l-42.666666-202.666666a5.333333 5.333333 0 0 0-5.333334-4.213334h-40a5.333333 5.333333 0 0 0-5.333333 6.613334l64 247.573333a5.333333 5.333333 0 0 0 5.333333 4h42.346667a5.333333 5.333333 0 0 0 5.333333-3.893333c14.933333-55.093333 40.586667-148.373333 49.226667-190.773334h0.373333c7.946667 38.826667 33.28 132.373333 48 190.666667a5.333333 5.333333 0 0 0 5.333334 4h42.666666a5.333333 5.333333 0 0 0 5.333334-3.893333l68.853333-247.573334a5.333333 5.333333 0 0 0-5.333333-6.72h-36.053334a5.333333 5.333333 0 0 0-5.333333 4c-11.52 46.72-39.146667 149.6-47.36 200.693334h-0.373333c-7.36-40.586667-35.36-147.04-49.76-200.8a5.333333 5.333333 0 0 0-5.706667-3.946667z" p-id="8403"></path></svg>',
				onClick: () => {
					console.log("导出Word");
					exportDocument('word')
				},
				tip: "导出Word"
			},
			{
				icon: '<svg t="1748916378385" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10277" width="256" height="256"><path d="M625.226667 390.293333V224a5.333333 5.333333 0 0 0-5.333334-5.333333h-506.133333a5.333333 5.333333 0 0 0-5.333333 5.333333v166.293333a5.333333 5.333333 0 0 0 5.333333 5.333334h506.133333a5.333333 5.333333 0 0 0 5.333334-5.333334z m-314.986667-79.466666a32.853333 32.853333 0 0 1-23.306667 7.146666h-14.24v25.866667a5.333333 5.333333 0 0 1-5.333333 5.333333h-15.413333a5.333333 5.333333 0 0 1-5.333334-5.333333V270.506667a5.333333 5.333333 0 0 1 5.333334-5.333334h37.813333a29.546667 29.546667 0 0 1 21.333333 6.72 25.013333 25.013333 0 0 1 7.04 19.04 25.813333 25.813333 0 0 1-7.893333 19.893334z m96 16.906666a34.56 34.56 0 0 1-8.48 12.48A28.213333 28.213333 0 0 1 385.866667 346.666667a62.08 62.08 0 0 1-15.466667 2.293333h-33.226667a5.333333 5.333333 0 0 1-5.333333-5.333333V270.506667a5.333333 5.333333 0 0 1 5.333333-5.333334h33.226667a45.92 45.92 0 0 1 18.4 3.093334 30.506667 30.506667 0 0 1 11.626667 9.066666 37.333333 37.333333 0 0 1 6.613333 13.493334 62.08 62.08 0 0 1 2.08 16 55.413333 55.413333 0 0 1-3.093333 20.906666z m80.8-49.866666a5.333333 5.333333 0 0 1-5.333333 5.333333h-27.466667a5.333333 5.333333 0 0 0-5.333333 5.333333v4a5.333333 5.333333 0 0 0 5.333333 5.333334h21.92a5.333333 5.333333 0 0 1 5.333333 5.333333V309.333333a5.333333 5.333333 0 0 1-5.333333 5.333334h-21.92a5.333333 5.333333 0 0 0-5.333333 5.333333v23.68a5.333333 5.333333 0 0 1-5.333334 5.333333h-15.36a5.333333 5.333333 0 0 1-5.333333-5.333333V270.506667a5.333333 5.333333 0 0 1 5.333333-5.333334h53.333334a5.333333 5.333333 0 0 1 5.333333 5.333334z" p-id="10278"></path><path d="M280.106667 282.24h-7.413334v18.72h6.346667a16.266667 16.266667 0 0 0 10.666667-2.613333 8.32 8.32 0 0 0 3.04-6.666667 9.226667 9.226667 0 0 0-2.613334-6.666667 13.546667 13.546667 0 0 0-10.026666-2.773333zM364.266667 284.213333h-6.506667v45.866667h6.4a26.666667 26.666667 0 0 0 11.573333-1.813333 12.266667 12.266667 0 0 0 5.333334-6.293334 39.946667 39.946667 0 0 0 1.92-14.56 28.213333 28.213333 0 0 0-4.32-18.293333 18.24 18.24 0 0 0-14.4-4.906667z" p-id="10279"></path><path d="M912 106.666667H201.173333a5.333333 5.333333 0 0 0-5.333333 5.333333v64a5.333333 5.333333 0 0 0 5.333333 5.333333H837.333333a5.333333 5.333333 0 0 1 5.333334 5.333334v510.666666a5.333333 5.333333 0 0 1-1.546667 3.733334l-88.213333 140.053333a5.333333 5.333333 0 0 1-3.733334 1.546667H275.84a5.333333 5.333333 0 0 1-5.333333-5.333334V434.08a5.333333 5.333333 0 0 0-5.333334-5.333333h-64a5.333333 5.333333 0 0 0-5.333333 5.333333V912a5.333333 5.333333 0 0 0 5.333333 5.333333h578.88a5.333333 5.333333 0 0 0 3.786667-1.546666l131.946667-183.786667a5.333333 5.333333 0 0 0 1.546666-3.786667V112a5.333333 5.333333 0 0 0-5.333333-5.333333z" p-id="10280"></path><path d="M378.666667 771.306667a28.693333 28.693333 0 0 0 17.28 27.146666 24.586667 24.586667 0 0 0 14.826666 4.32c24.693333 0 53.706667-27.786667 84-81.493333a665.066667 665.066667 0 0 1 117.333334-37.706667 118.56 118.56 0 0 0 72.906666 30.293334c16 0 49.386667 0 49.386667-35.84 0-12.373333-6.186667-33.973333-52.48-35.2a297.333333 297.333333 0 0 0-62.4 6.186666A283.2 283.2 0 0 1 558.453333 570.666667c17.28-55.573333 18.506667-92.053333 5.333334-110.56a32.426667 32.426667 0 0 0-25.92-12.96 30.826667 30.826667 0 0 0-30.293334 16c-18.506667 30.24 7.413333 88.32 19.146667 112A672 672 0 0 1 474.666667 697.173333c-94.133333 40.746667-96 65.493333-96 74.133334z m33.333333 2.453333l-3.093333 1.226667a89.333333 89.333333 0 0 1 35.2-29.013334 61.76 61.76 0 0 1-32.053334 27.786667z m268.693333-98.826667c19.146667 0 23.466667 4.32 22.24 7.413334a39.2 39.2 0 0 1-19.146666 1.866666 72.373333 72.373333 0 0 1-29.066667-7.413333 121.76 121.76 0 0 1 26.026667-1.866667zM532.48 481.013333a5.706667 5.706667 0 0 1 4.32-1.28h3.093333a75.413333 75.413333 0 0 1-1.226666 51.893334 75.68 75.68 0 0 1-6.186667-50.613334z m12.373333 142.026667l2.453334-0.586667a289.76 289.76 0 0 0 38.933333 47.52l-1.866667 1.28a588.16 588.16 0 0 0-66.72 19.146667l-1.813333-0.64c10.453333-21.6 20.373333-43.84 29.013333-66.72z" p-id="10281"></path></svg>',
				onClick: () => {
					console.log("导出PDF");
					exportDocument('pdf')
				},
				tip: "导出PDF"
			},
			"|",{
				icon: '<svg t="1749695190792" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="14675" width="256" height="256"><path d="M238.312727 430.545455v418.90909h547.374546v-418.90909z m-93.090909-3.723637A89.367273 89.367273 0 0 1 232.727273 337.454545h558.545454a89.367273 89.367273 0 0 1 89.367273 89.367273v426.356364A89.367273 89.367273 0 0 1 791.272727 942.545455H232.727273a89.367273 89.367273 0 0 1-89.367273-89.367273z" fill="#302C2C" p-id="14676"></path><path d="M362.589091 597.178182a42.821818 42.821818 0 1 0-42.356364-42.356364 42.821818 42.821818 0 0 0 42.356364 42.356364zM661.410909 597.178182a42.821818 42.821818 0 1 0-42.821818-42.356364 42.356364 42.356364 0 0 0 42.821818 42.356364zM426.821818 682.821818a42.821818 42.821818 0 1 0 0 85.178182z m170.356364 85.178182a42.821818 42.821818 0 1 0 0-85.178182z m-170.356364 0h170.356364v-85.178182H426.821818z" fill="#302C2C" p-id="14677"></path><path d="M512 166.632727a46.545455 46.545455 0 0 1 46.545455 46.545455v170.821818a46.545455 46.545455 0 0 1-93.09091 0V213.178182a46.545455 46.545455 0 0 1 46.545455-46.545455zM85.178182 508.276364a46.545455 46.545455 0 0 1 46.545454 46.545454v170.356364a46.545455 46.545455 0 0 1-93.090909 0v-170.356364a46.545455 46.545455 0 0 1 46.545455-46.545454zM938.821818 508.276364a46.545455 46.545455 0 0 1 46.545455 46.545454v170.356364a46.545455 46.545455 0 1 1-93.090909 0v-170.356364a46.545455 46.545455 0 0 1 46.545454-46.545454z" fill="#302C2C" p-id="14678"></path><path d="M512 174.545455a3.723636 3.723636 0 0 0 3.723636-3.723637 3.723636 3.723636 0 1 0-7.447272 0 3.723636 3.723636 0 0 0 3.723636 3.723637z m-89.367273-3.723637A89.367273 89.367273 0 1 1 512 259.723636a89.367273 89.367273 0 0 1-89.367273-88.901818z" fill="#302C2C" p-id="14679"></path></svg>',
				onClick: () => {
					openChat()
				},
				tip: "AI对话"
			},
			"|", "ai",
		] : [],
		toolbarExcludeKeys: ["source-code", "fullscreen", "video", "break", "emoji", "ai"],
		textSelectionBubbleMenu: {
			enable: true,
			items: ["ai", "Bold", "Italic", "Underline", "Strike", "code"],
		},
		onCreated: async (editor) => {
			await updateOutLine(editor)
			await countWords()
			await calcHeight()
		},
		onChange: async (editor) => {
			await updateOutLine(editor)
			await countWords()
			await calcHeight()
			emit('change')
		},
	})

	// 初始化消息
	initMessages();
})

onUnmounted(() => {
	aiEditor && aiEditor.destroy();
})

// 计算高度
const calcHeight = () => {
	const pageHeader = document.querySelector('.header');
	const directory = document.querySelector('.aie-header-panel');
	let headerHeight = -28;
	if (pageHeader) {
		headerHeight += pageHeader.clientHeight;
	}
	if (directory) {
		headerHeight += directory.clientHeight;
	}
	document.documentElement.style.setProperty('--directory-header-height', `${headerHeight}px`);
}

// 初始化消息
const initMessages = () => {
	const defaultMessage = [
		{ role: 'custom', content: '总结文档主要内容'},
		{ role: 'custom', content: '总结写作思路'},
		{ role: 'custom', content: '润色优化文档' },
		{ role: 'custom', content: '缩写该文档，主题思想不变'},
		{ role: 'custom', content: '优化文档内容，主题思想不变' },
		{ role: 'custom', content: '对文档内容进行扩写'},
		{ role: 'custom', content: '给文档起一个标题' },
		{ role: 'custom', content: '给文档增加摘要部分'},
	]
	const shuffled = [...defaultMessage].sort(() => 0.5 - Math.random());
	const selectedMessages = shuffled.slice(0, 4);
	messages.value = [
		{ role: 'tips', content: '你可能想要：'},
	];
	messages.value.push(...selectedMessages);
}

// 字数统计
const countWords = () => {
	// return;
	// const footerDom = document.querySelector(".aie-container-footer aie-footer") as HTMLElement;
	// const spanElement = footerDom.querySelector('span');
	// if (spanElement) {
	// 	const spans = spanElement.textContent?.split(',');
    //     if (spans && spans.length > 0) {
    //         const parent = spanElement.parentElement as HTMLElement;
	// 		spanElement.remove()

	// 		const span1 = document.createElement("span");
	// 		span1.textContent = (spans[1] || spans[0]).replace('Characters', '字数');
	// 		parent.appendChild(span1);

			// const span0 = document.createElement("span");
			// span0.style.marginLeft = 'auto';
			// span0.textContent = spans[0];
			// parent.appendChild(span0);
        // }
    // }
}

// 更新目录
const updateOutLine = (editor: AiEditor) => {
	const outlineContainer = document.querySelector("#outline");
	while (outlineContainer?.firstChild) {
		outlineContainer.removeChild(outlineContainer.firstChild)
	}

	const outlines = editor.getOutline();
	for (let outline of outlines) {
		const child = document.createElement("div")
		child.classList.add(`aie-title${outline.level}`)
		child.style.marginLeft = `${14 * (outline.level - 1)}px`
		child.innerHTML = `<a href="#${outline.id}">${outline.text}</a>`
		child.addEventListener("click", (e) => {
			e.preventDefault();
			const el = editor.innerEditor.view.dom.querySelector(`#${outline.id}`) as HTMLElement;
			el.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
			setTimeout(() => {
				editor.focusPos(outline.pos + outline.size - 1)
			}, 1000)
		})
		outlineContainer?.appendChild(child)
	}
}

// 切换标签
const ontab = (type: string) => {
	tabType.value = type;
}

// 输入框自动增高
const adjustTextareaHeight = () => {
	const textarea = textareaRef.value as HTMLTextAreaElement;
	if (textarea) {
		textarea.style.height = 'auto';
		const newHeight = Math.min(textarea.scrollHeight, 200);
		textarea.style.height = `${newHeight}px`;
	}
}

// 发送消息
const sendMessage = () => {
	const textarea = textareaRef.value as HTMLTextAreaElement;
	if (textarea && textarea.value.trim()) {
		const message = textarea.value.trim();
		// 添加用户消息
		messages.value.push({
			role: 'user',
			content: message
		});

		// 清空输入框
		textarea.value = '';
		textarea.style.height = 'auto';
		textarea.focus();

		// 滚动到底部
		scrollBottom();
		isLoading.value = true;
		abortController.value = new AbortController();
		replyMessage(message).finally(() => {
			isLoading.value = false;
			abortController.value = null;
		})
	}
}

// 发送消息
const sendMessage1 = (message: any) => {
	if (message.role === 'custom') {
		messages.value.push({
			role: 'user',
			content: message.content
		});
		scrollBottom();
		isLoading.value = true;
		abortController.value = new AbortController();
		const content = message.content + '，内容如下：' + aiEditor?.getText();
		replyMessage(content).finally(() => {
			isLoading.value = false;
			abortController.value = null;
		})
	}
}

// 调用模型回复消息
const replyMessage = async (content: string = "") => {
	try {
		// 构建历史消息数组
		const historyMessages = messages.value
			.filter(msg => msg.role !== 'system' && msg.role !== 'tips' && msg.role !== 'custom')
			.map(msg => ({
				role: msg.role,
				content: msg.content
			})).slice(0, -1)

		const response = await fetch(llm_url + '/stream', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'Authorization': `Bearer ${llm_key}`
			},
			body: JSON.stringify({
				"model": llm_model,
				"messages": [
					{
						"role": "system",
						"content": "你是一个专业的AI文档助手，专注于帮助用户高效创建、编辑和优化文档内容。你的主要职责包括：1) 根据用户需求生成高质量的文档内容；2) 对现有文档进行润色、改写和优化；3) 提供文档结构建议；4) 回答与文档创作相关的专业问题。请确保你的回复专业、准确且符合文档写作规范。"
					},
					...historyMessages,
					{
						"content": content,
						"role": "user"
					}
				],
				"temperature": 0.7,
				"top_p": 0.5,
				"max_tokens": 1024,
				"stream": false
			}),
			signal: abortController.value?.signal
		});

		if (!response.ok) {
			throw new Error('网络响应异常');
		}

		const reader = response.body?.getReader();
		const decoder = new TextDecoder('utf-8');
		let result = '';
		let done = false;

		while (!done) {
			const { value, done: streamDone } = await reader!.read();
			done = streamDone;
			if (done) break;

			const chunk = decoder.decode(value, { stream: true });
			result += chunk;
		}
		// const result = await response.text()
		updateChat(result);
	} catch (error) {
		// @ts-ignore
		if (error.name === 'AbortError') {
			return;
		}
		console.error('请求失败:', error);
		messages.value.push({
			role: 'assistant',
			content: '请求失败，请稍后再试',
		});
	} finally {
		isLoading.value = false;
	}
}

// 消息渲染展示
const updateChat = (message: string) => {
	console.log(message)
	const fullContent = message
		// .replace(/<think>.*?<\/think>/gs, '')
		.split('\n')
		.map(data => data.replace('data:', ''))
		.filter(data => data && data !== '[DONE]')
		.reduce((acc, data) => {
			try {
				// const content = JSON.parse(data).choices?.[0]?.delta?.content || '';
				const content = JSON.parse(data).result.output.text || '';
				return acc + content;
			} catch (e) {
				console.error('解析错误:', e);
				return acc;
			}
		}, '');

	const messageIndex = messages.value.push({
		role: 'assistant',
		content: ''
	}) - 1;

	// 逐字显示效果
	let currentIndex = 0;
	const interval = setInterval(() => {
		if (currentIndex < fullContent.length) {
			messages.value[messageIndex].content = marked.parse(fullContent.substring(0, ++currentIndex));
			scrollBottom();
		} else {
			clearInterval(interval);
		}
	}, 50);
}

// 停止回复消息
const stopGeneration = () => {
	if (abortController.value) {
		abortController.value.abort(); // 中止请求
		isLoading.value = false;
		abortController.value = null;
	}
}

// 消息滚动到底部
const scrollBottom = () => {
	setTimeout(() => {
		const chatContent = document.querySelector('.chat-content');
		if (chatContent) {
			chatContent.scrollTo({
				top: chatContent.scrollHeight,
				behavior: 'smooth'
			});
		}
	}, 100);
}

// 处理Enter键事件
const handleEnterKey = (e: KeyboardEvent) => {
	if (e.shiftKey) {
		// 如果按住Shift+Enter，插入换行
		const textarea = textareaRef.value as HTMLTextAreaElement;
		const startPos = textarea.selectionStart;
		const endPos = textarea.selectionEnd;
		textarea.value = textarea.value.substring(0, startPos) + "\n" + textarea.value.substring(endPos);
		adjustTextareaHeight();
	} else {
		// 直接按Enter发送消息
		sendMessage();
	}
}

// 复制消息内容
const copyMessage = (content: string) => {
	// 创建一个临时div来提取纯文本内容
	const tempDiv = document.createElement('div');
	tempDiv.innerHTML = content;
	const plainText = tempDiv.textContent || tempDiv.innerText || '';

	navigator.clipboard.writeText(plainText).then(() => {
		showToastMessage('已复制到剪贴板', 'success');
	}).catch(err => {
		console.error('复制失败:', err);
		showToastMessage('复制失败', 'error');
	});
}

// 重新生成内容
const regenerateMessage = async (index: number) => {
	// 获取要重新生成的消息之前的用户消息
	// @ts-ignore
	const userMessageIndex = messages.value.findLastIndex(
		(msg: any, i: any) => i < index && msg.role === 'user'
	);

	if (userMessageIndex === -1) return;

	// 设置loading状态
	isLoading.value = true;

	try {
		// 移除旧的AI回复
		messages.value.splice(index, 1);

		// 获取用户原始消息内容
		const userMessage = messages.value[userMessageIndex].content;

		// 调用API重新生成回复
		await replyMessage(userMessage);
	} finally {
		isLoading.value = false;
	}
}

// 重写指令
const rewriteInstruction = (index: number) => {
	const textarea = textareaRef.value as HTMLTextAreaElement;
	if (textarea) {
		textarea.value = messages.value[index].content;
		textarea.focus();
	}
}

// 应用消息
const applyMessage = (content: string) => {
	aiEditor?.clear();
	aiEditor?.focus().insert(content);
}

// 追加消息
const insertMessage = (content: string) => {
	aiEditor?.focus().insert(content);
}

// 新建对话
const newChat = () => {
	initMessages();
	scrollBottom();
}

// 清除历史消息
const clearHistory = () => {
	messages.value = [];
	newChat();
}

// 优化提示词
const optimizePrompt = async () => {
	const textarea = textareaRef.value as HTMLTextAreaElement;
	if (textarea && textarea.value.trim()) {
		const originalPrompt = textarea.value.trim();
		isLoading.value = true;

		try {
			// 调用API优化提示词
			const optimized = await optimizePromptAPI(originalPrompt);
			textarea.value = optimized;
			textarea.focus();
			adjustTextareaHeight();
		} finally {
			isLoading.value = false;
		}
	}
}

// 调用API优化提示词
const optimizePromptAPI = async (prompt: string) => {
	try {
		const response = await fetch(llm_url, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'Authorization': `Bearer ${llm_key}`
			},
			body: JSON.stringify({
				"model": llm_model,
				"messages": [
					{
						"role": "system",
						"content": "你是一个提示词优化助手，请将用户输入的提示词优化得更清晰、具体和有效，直接返回优化后的提示词内容，不要添加任何解释。"
					},
					{
						"content": "请帮我优化这个提示词：" + prompt,
						"role": "user"
					}
				],
				"stream": false
			})
		});

		if (!response.ok) {
			throw new Error('网络响应异常');
		}

		const data = await response.text();
		const cleanedData = data.replace(/<think>.*?<\/think>/gs, '');
		return cleanedData;
	} catch (error) {
		console.error('优化提示词失败:', error);
		return prompt;
	}
}

// 在methods中添加清除输入的方法
const clearInput = () => {
	const textarea = textareaRef.value as HTMLTextAreaElement;
	if (textarea) {
		textarea.value = '';
		textarea.style.height = 'auto';
		textarea.focus();
	}
}

// 导入文档 word
const importDocument = () => {
	// 创建隐藏的文件输入元素
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    
    input.onchange = async (e) => {
        const file = (e.target as HTMLInputElement).files?.[0];
        if (!file) return;

        try {
            const formData = new FormData();
            formData.append('file', file);

            const response = await fetch(`${import_api}/word`, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error('上传失败');
            }

            const result = await response.json();
			console.log(result, "返回解决")
            if (result && result.html) {
                // 清空编辑器并插入解析后的内容
                aiEditor?.clear();
				setTimeout(() => {
					aiEditor?.setContent(parseHtml(result.html));
				}, 1000);
            }
        } catch (error) {
            console.error('导入Word文档失败:', error);
			showToastMessage('上传失败了', 'error');
        }
    };
    
    // 触发文件选择对话框
    input.click();
}
// 导出文档 word, pdf
const exportDocument = (type: string = "word") => {
	// const url = `${export_api}/${type}`;
	const url = `${export_api}/md`;
	let fileName = 'export.docx';
	if (type === "pdf") {
		fileName = 'export.pdf';
	}
	fetch(url, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json'
		},
		body: JSON.stringify({
			// html: aiEditor?.getHtml()
			md: aiEditor?.getMarkdown(),
			type: type
		})
	}).then(response => {
		console.log(response);
		if (response.ok) {
			return response.blob();
		}
	}).then(blob => {
		console.log(blob);
		if (blob) {
			const link = document.createElement('a')
			link.style.display = 'none'
			link.href = URL.createObjectURL(blob)
			link.download = fileName
			document.body.appendChild(link)
			link.click()
			// 释放的 URL 对象以及移除 a 标签
			URL.revokeObjectURL(link.href)
			document.body.removeChild(link)
		}
	})
}

// 关闭聊天对话面板
const showChatPanel = ref(false);
const closeChat = () => {
    showChatPanel.value = false;
}
const openChat = () => {
    showChatPanel.value = true;
}

// 目录面板操作
const showDirectory = ref(false);
const closeDirectory = () => {
    showDirectory.value = false;
}
const openDirectory = () => {
    showDirectory.value = true;
}

// 编辑器内容滚动
const scrollToBottom = () => {
    const editorContainer = document.querySelector('.aie-container-panel-box');
    if (editorContainer) {
        editorContainer.scrollTo({
            top: editorContainer.scrollHeight,
            behavior: 'smooth'
        });
    }
}

// 获取编辑器的内容
const getEditorContent = (type: string = "text") => {
	if (type === "text") {
		return aiEditor?.getText();
	}
	if (type === "html") {
		return aiEditor?.getHtml();
	}
	if (type === "markdown") {
		return aiEditor?.getMarkdown();
	}
}
const getEditorWords = () => {
	return aiEditor?.getText().length;
}
const setEditorContent = (content: string) => {
	aiEditor?.setContent(parseHtml(content));
}

const insertEditorContent = (content: string) => {
	aiEditor?.insert(content);
}

const getAiEditor = () => {
	return aiEditor;
}

const clearEditorContent = () => {
	aiEditor?.clear();
}

defineExpose({
	getEditorContent,
	setEditorContent,
	clearEditorContent,
	insertEditorContent,
	getEditorWords,
	getAiEditor,
	scrollToBottom,
	parseHtml
})

</script>


<style>
html,
body {
	overflow: hidden;
	height: 100vh;
	margin: 0;
	padding: 0;
}

.page-header {
	background-color: #fff;
	height: 35px;
	line-height: 35px;
	padding: 0 2rem;
	display: flex;
	position: sticky;
	border-bottom: 1px solid #efefef;
	top: 0;
	z-index: 1;
}

.logo a {
	font-size: 20px;
	font-weight: 500;
	color: #000000;
	text-decoration: none;
}


.aie-container {
	border: none !important;
}

.aie-header-panel {
	position: sticky;
	z-index: 1;
}

.aie-header-panel aie-header>div {
	align-items: center;
	padding-left: 10px;
}


.aie-main {
	position: relative;
	display: flex;
	width: 100%;
	height: calc(100vh - 60px);
	overflow: visible;
}

.aie-main > div{
	height: 100%;
}

.aie-container-panel {
	flex: 1;
	height: 100%;
	padding-top: 8px;
	overflow: hidden;
	box-sizing: border-box;
}
.aie-container-panel-box{
	overflow-y: auto;
	overflow-x: hidden;
	height: 100%;
	box-sizing: border-box;
	scrollbar-width: thin;
    scrollbar-color: rgba(0, 0, 0, 0.1) transparent;
}
.aie-container-panel-box::-webkit-scrollbar {
    width: 4px;
    height: 4px;
}
.aie-container-panel-box::-webkit-scrollbar-track {
    background: transparent;
}
.aie-container-panel-box::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 2px;
}
.aie-container-main {
	margin: 0 auto;
    max-width: 800px;
    width: calc(100% - 30px);
    min-height: 100%;
    padding: 15px 50px;
    background-color: #fff;
    box-sizing: border-box;
	padding-bottom: 50px;
}

.aie-ai-content{
	position: relative;
	transition: all 0.3s ease;
    transform: translateX(0);
    opacity: 1;
	z-index: 1;
}
.aie-ai-content.hidden {
    transform: translateX(100%);
    opacity: 0;
    width: 0;
    margin: 0;
    border: none;
    pointer-events: none;
}

.aie-main > .aie-menu-button{
	cursor: pointer;
    color: rgba(0,0,0,.4);
    font-size: 12px;
    font-weight: 500;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    top: calc(20% - 16px);
    line-height: 16px;
    left: -1px;
    padding: 7px 9px;
    display: block;
    position: fixed;
    margin: 0;
    z-index: 2000;
    opacity: 0;
    background-color: var(--bg-lv4-strong);
    border: 1px solid transparent;
    -webkit-transition: all .3s ease;
    transition: all .3s ease;
    text-align: center;
	height: 20px;
}

.aie-menu-content{
	position: relative;
	width: 330px;
	transition: all 0.3s ease;
    transform: translateX(0);
    opacity: 1;
}
.aie-menu-content.hidden {
    transform: translateX(-100%);
    opacity: 0;
    width: 0;
    margin: 0;
    border: none;
    pointer-events: none;
}

.aie-directory {
	position: absolute;
	width: 100%;
	height: calc(100% - var(--directory-header-height, 60px));
	margin: 8px 0 0 8px;
	overflow-y: auto;
	border: 1px solid rgb(229 231 235);
	box-sizing: border-box;
	background: #fff;
	padding: 10px;
	border-radius: 4px;
}

.aie-directory a {
	height: 30px;
	font-size: 14px;
	color: #000000a3;
	text-indent: 4px;
	line-height: 30px;
	text-decoration: none;
	width: 100%;
	display: inline-block;
	margin: 0;
	padding: 0;
	white-space: nowrap;
	overflow: hidden;
	-o-text-overflow: ellipsis;
	text-overflow: ellipsis;
}

.aie-directory a:hover {
	cursor: pointer;
	background-color: #334d660f;
	border-radius: 4px;
}

.aie-title1 {
	font-size: 14px;
	font-weight: 500;
}

.aie-title2,
.aie-title3,
.aie-title4,
.aie-title5,
.aie-title6 {
	font-size: 12px;
}
.directory-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 0 10px;
    border-bottom: 1px solid rgb(229 231 235);
    margin: 0 0 10px;
}
.directory-header h5 {
    color: #000000c4;
    font-size: 16px;
    text-indent: 4px;
    margin: 0;
}
.directory-header .btn {
    padding: 0 4px;
    border-radius: 4px;
    cursor: pointer;
}
.directory-header .btn:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

/* @media screen and (max-width: 1280px) {
	.aie-directory {
		height: calc(100% - 45px);
	}

	.aie-ai-chat {
		height: calc(100% - 45px);
	}

} */
/* @media screen and (max-width: 1488px) {
	.aie-directory {
		height: calc(100% - 90px)!important;
	}

	.aie-ai-chat {
		height: calc(100% - 90px) !important;
	}
} */

.aie-container-footer {
	background-color: #fff;
	width: 100%;
	position: fixed;
	bottom: 0;
}

.aie-container aie-footer>div span {
	margin-left: 60px;
}

.aie-ai-chat {
	margin: 8px 8px 0 0;
	height: calc(100% - var(--directory-header-height, 60px));
	width: 358px;
	background-color: #fff;
	border: 1px solid rgb(229 231 235);
	border-radius: 4px;
	box-sizing: border-box;
}

.chat-tabar {
	display: flex;
	height: 40px;
	padding: 0 10px;
	align-items: center;
	border-bottom: 1px solid rgb(229 231 235);
}

.chat-tabar .tab {
	position: relative;
	display: flex;
	align-items: center;
	height: 100%;
	font-size: 14px;
	margin: 0 5px;
	padding: 0px 5px;
	color: rgba(0, 0, 0, .64);
	cursor: pointer;
	font-size: 16px;
	font-weight: bold;
}

.chat-tabar .tab.active {
	color: #000000;
	font-weight: 500;
}

.chat-tabar .tab.active::before{
	content: '';
	position: absolute;
	left: 0;
	right: 0;
	bottom: 0;
	border-bottom: 2px solid #000000;
}

.chat-tabar .tab .icon-tab{
	width: 16px;
	height: 16px;
	display: inline-block;
	margin-right: 4px;
	vertical-align: middle;
	background: url(./assets/img/icon-ai.png) no-repeat center;
}


.tab-op {
	margin-left: auto;
	display: flex;
	gap: 4px;
}

.tab-op .btn {
	padding: 0;
	width: 24px;
	height: 24px;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 4px;
	cursor: pointer;
	position: relative;
}

.tab-op .btn:hover {
	background-color: rgba(0, 0, 0, 0.05);
}

.tab-op .btn:hover::after {
	content: attr(title);
	position: absolute;
	bottom: 100%;
	left: 50%;
	transform: translateX(-50%);
	background-color: rgba(0, 0, 0, 0.8);
	color: white;
	padding: 4px 8px;
	border-radius: 4px;
	font-size: 12px;
	white-space: nowrap;
	z-index: 10;
	margin-top: 5px;
}

.chat-main {
	height: calc(100% - 41px);
}
.chat-main .panel{
	height: 100%;
	box-sizing: border-box;
}

.chat-input {
	height: 125px;
	padding: 10px;
	border-top: 1px solid rgb(229 231 235);
	background-color: #fff;
	border-bottom-right-radius: 8px;
	border-bottom-left-radius: 8px;
	box-sizing: border-box;
}

/* .chat-input .input {
	position: relative;
} */

.chat-input .input-text {
	display: block;
	width: 100%;
	/* min-height: 100px;
	max-height: 200px; */
	height: 100%!important;
	border-radius: 4px;
	border: 1px solid rgb(229 231 235);
	padding: 10px;
	resize: none;
	overflow-y: auto;
	outline: none;
	box-sizing: border-box;
	transition: height 0.2s ease;
}

.chat-input .input-text:focus {
	border: 1px solid rgb(229 231 235);
	box-shadow: none;
}

.btn-box {
	height: 25px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 12px;
	transform: translateY(-5px);
}

.btn-group {
	display: flex;
	gap: 15px;
}

.btn-box .btn {
	padding: 3px 6px;
	border-radius: 4px;
	cursor: pointer;
	font-size: 12px;
	transition: all 0.2s ease;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

.send-btn {
	width: 16px;
	height: 15px;
	background: url(./assets/img/icon-send.png) no-repeat center;
	cursor: pointer;
}

.send-btn:hover {
	opacity: 0.8;
}

.stop-btn {
	background-color: #ff4d4f;
	color: white;
}

.stop-btn:hover {
	background-color: #ff7875;
	box-shadow: 0 2px 4px rgba(255, 77, 79, 0.3);
}

.optimize-btn {
	font-size: 14px;
	color: #12D0B0;
	cursor: pointer;
}
.optimize-btn::before{
	content: '';
	display: inline-block;
	width: 16px;
	height: 16px;
	background: url(./assets/img/icon-yh.png) no-repeat center;
	vertical-align: middle;
	margin: -3px 2px 0 0;
}

.optimize-btn:hover {
	opacity: 0.8;
}

.clear-btn {
	font-size: 14px;
	color: #B4BFD0;
	cursor: pointer;
}

.clear-btn:hover {
	opacity: 0.8;
}


.chat-content {
	height: calc(100% - 150px);
	overflow-x: hidden;
	overflow-y: auto;
	padding: 10px;
	box-sizing: border-box;
}

.message {
	display: flex;
	flex-direction: column;
	margin-bottom: 8px;
}

.message-bubble {
	max-width: 80%;
	padding: 10px;
	border-radius: 8px;
	word-wrap: break-word;
	font-size: 14px;
}

.message.user .message-bubble {
	background-color: #e6f7ff;
	color: #333;
	align-self: flex-end;
}

.message.assistant .message-bubble {
	background-color: #f0f0f0;
	color: #333;
	align-self: flex-start;
}
.message.custom .message-bubble {
	background-color: #f0f0f0;
	color: #333;
	align-self: flex-start;
	cursor: pointer;
}
.message.tips .message-bubble{
	background-color: #f0f0f0;
	color: #333;
	align-self: flex-start;
}
.message.tips .message-bubble span{
	font-weight: bold;
}

.message-content p {
	margin: 0;
}

.message-actions {
	margin-top: 4px;
	display: flex;
	gap: 6px;
}

.message-actions.user {
	align-self: flex-end;
}

.action-btn {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 24px;
	border-radius: 2px;
	cursor: pointer;
	box-sizing: border-box;
	color: var(--text-medium, rgba(0, 0, 0, 0.48));
	font-family: 'PingFang SC';
	font-size: 10px;
	font-style: normal;
	font-weight: 400;
	line-height: 13px;
	position: relative;
}

.action-btn:hover {
	background-color: rgba(0, 0, 0, 0.05);
}

.action-btn:hover::after {
	content: attr(title);
	position: absolute;
	bottom: 100%;
	left: 50%;
	transform: translateX(-50%);
	background-color: rgba(0, 0, 0, 0.8);
	color: white;
	padding: 4px 8px;
	border-radius: 4px;
	font-size: 12px;
	white-space: nowrap;
	z-index: 10;
	margin-bottom: 5px;
}

/** 消息提示样式 */
.toast-container {
    position: fixed;
    top: 150px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
}
.toast-message {
    color: white;
    padding: 6px 24px;
    border-radius: 6px;
    font-size: 14px;
    display: flex;
    align-items: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    animation: fadeInOut 2s ease-in-out;
}
.toast-message.success {
    background-color: #95de64; /* 浅绿色 */
}
.toast-message.error {
    background-color: #ff7875; /* 浅红色 */
}
.toast-message.warning {
    background-color: #ffd666; /* 浅黄色 */
}
.toast-icon {
    margin-right: 8px;
    font-size: 16px;
	margin-top: 4px;
}
@keyframes fadeInOut {
    0% {
        opacity: 0;
        transform: translateY(20px);
    }
    20% {
        opacity: 1;
        transform: translateY(0);
    }
    80% {
        opacity: 1;
        transform: translateY(0);
    }
    100% {
        opacity: 0;
        transform: translateY(-20px);
    }
}

/** 对话 loading 样式 */
.loading-dots {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 20px;
}

.loading-dots .dot {
	width: 8px;
	height: 8px;
	margin: 0 4px;
	background-color: #888;
	border-radius: 50%;
	animation: bounce 1.4s infinite ease-in-out both;
}

.loading-dots .dot:nth-child(1) {
	animation-delay: -0.32s;
}

.loading-dots .dot:nth-child(2) {
	animation-delay: -0.16s;
}

@keyframes bounce {

	0%,
	80%,
	100% {
		transform: scale(0);
	}

	40% {
		transform: scale(1);
	}
}
</style>